package pfq.demo.designpattern.chainofresponsibilitypattern.okhttp;

import java.util.List;

public class RealInterceptorChain implements Interceptor.Chain {

    private Request mRequest;
    private int mIndex;
    private List<Interceptor> mInterceptors;

    public RealInterceptorChain(Request request, int index, List<Interceptor> interceptors) {
        mRequest = request;
        mIndex = index;
        mInterceptors = interceptors;
    }

    @Override
    public Response proceed(Request request) {

        if (mIndex >= mInterceptors.size()) {
            System.out.println("index数组越界");
            return null;
        }

        // 取出当前index的拦截器
        Interceptor interceptor = mInterceptors.get(mIndex);
        // 执行拦截器的拦截方法
        // 此处是责任链模式的关键所在：并新建一个条链，在该链中可以取出下一条拦截器对象，关键代码是index+1
        return interceptor.intercept(new RealInterceptorChain(mRequest, mIndex + 1, mInterceptors));

    }

    @Override
    public Request request() {
        return mRequest;
    }
}
